﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.IO;

namespace Preyla
{
    public partial class FormComponent : Form
    {
        IDatabase DBManager = new AccessManager(Properties.Settings.Default.ConnectionString);

        List<int> DeletedComponents = new List<int>();

        Color DefaultColor;
        Color AlternatingDefaultColor;

        public FormComponent()
        {
            InitializeComponent();
        }

        private void CancelButton_Click(object sender, EventArgs e)
        {
            Close();
        }

        private void ComponentTable_CellContentDoubleClick(object sender, DataGridViewCellEventArgs e)
        {
            if (e.ColumnIndex == 4 && e.RowIndex >= 0)
            {
                OpenFileDialog openFile = new OpenFileDialog();

                openFile.InitialDirectory = Directory.GetCurrentDirectory() + "\\Images";
                openFile.Filter = "Image | *.png";
                openFile.RestoreDirectory = true;

                if (openFile.ShowDialog() == DialogResult.OK)
                {
                    try
                    {
                        int index = openFile.FileName.IndexOf(openFile.InitialDirectory);

                        if (index == 0)
                        {
                            Image image = Image.FromFile(openFile.FileName);

                            if (image.Width != 64 || image.Height != 42)
                            {
                                MessageBox.Show("Only 64x42 images are acceptable");

                                return;
                            }

                            ComponentTable[4, e.RowIndex].Value = image;
                            ComponentTable[5, e.RowIndex].Value = openFile.FileName.Substring(openFile.InitialDirectory.Length + 1, openFile.FileName.Length - openFile.InitialDirectory.Length - 1);
                        }
                        else
                        {
                            MessageBox.Show("Copy that image to /Images folder");
                        }
                        
                    }
                    catch (Exception)
                    {
                        MessageBox.Show("Open file error");
                    }
                }
            }
        }

        private void FormComponent_Load(object sender, EventArgs e)
        {
            DBManager.Open();

            string ImagePath = Directory.GetCurrentDirectory() + "\\Images\\";

            ComponentTable[4, 0].Value = Image.FromFile(ImagePath + "Unknown.png");
            ComponentTable[5, 0].Value = "Unknown.png";

            DefaultColor = ComponentTable.DefaultCellStyle.BackColor;
            AlternatingDefaultColor = ComponentTable.AlternatingRowsDefaultCellStyle.BackColor;

            Read();
        }

        void Read()
        {
            string[][] Data = DBManager.ExecuteReader("SELECT Objects.ID, [Name], MTBF, MTTR, [Image] FROM Objects WHERE NOT EXISTS (SELECT ID FROM Links WHERE Links.ID = Objects.ID);");

            for (int i = 0; i < Data.Length; i++)
            {
                ComponentTable.Rows.Add();
                ComponentTable[0, ComponentTable.Rows.Count - 2].Value = Data[i][0];
                ComponentTable[1, ComponentTable.Rows.Count - 2].Value = Data[i][1];
                ComponentTable[2, ComponentTable.Rows.Count - 2].Value = Data[i][2];
                ComponentTable[3, ComponentTable.Rows.Count - 2].Value = Data[i][3];

                string ImagePath = Directory.GetCurrentDirectory() + "\\Images\\";
                
                try
                {
                    ComponentTable[4, ComponentTable.Rows.Count - 2].Value = Image.FromFile(ImagePath + Data[i][4]);
                    ComponentTable[5, ComponentTable.Rows.Count - 2].Value = Data[i][4];
                }
                catch(Exception e)
                {
                    if (File.Exists(ImagePath + "Unknown.png"))
                    {
                        ComponentTable[4, ComponentTable.Rows.Count - 2].Value = Image.FromFile(ImagePath + "Unknown.png");
                        ComponentTable[5, ComponentTable.Rows.Count - 2].Value = "Unknown.png";
                    }
                }
            }
        }

        bool Save()
        {
            for (int i = 0; i < ComponentTable.Rows.Count - 1; i++)
            {
                try
                {
                    if (ComponentTable[1, i].Value == null)
                    {
                        MessageBox.Show("Component name is empty");

                        return false;
                    }

                    string Name = ComponentTable[1, i].Value.ToString().Trim();

                    if (ComponentTable[2, i].Value == null || ComponentTable[3, i].Value == null)
                    {
                        MessageBox.Show("Component parameters are empty");

                        return false;
                    }
                    try
                    {
                        int MTBF = Int32.Parse(ComponentTable[2, i].Value.ToString());
                        int MTTR = Int32.Parse(ComponentTable[3, i].Value.ToString());
                        if (MTBF <= 0 || MTTR <= 0)
                        {
                            MessageBox.Show("MTBF and MTTR must be greater than 0");

                            return false;
                        }
                    }
                    catch (Exception ex)
                    {
                        MessageBox.Show("MTBF and MTTR must be a digits");

                        return false;
                    }

                    if (String.IsNullOrEmpty(Name))
                    {
                        MessageBox.Show("Component name is empty");

                        return false;
                    }

                    for (int j = 0; j < ComponentTable.Rows.Count - 1; j++)
                    {
                        if (i == j) continue;
                        if (Name.CompareTo(ComponentTable[1, j].Value.ToString()) == 0)
                        {
                            MessageBox.Show("Component name " + Name + " is used twice");

                            return false;
                        }
                    }

                    if (ComponentTable[0, i].Value != null)
                    {
                        DBManager.ExecuteNonQuery(String.Format("UPDATE Objects SET [Name]='{1}', MTBF={2}, MTTR={3}, [Image]='{4}' WHERE ID = {0};", ComponentTable[0, i].Value, ComponentTable[1, i].Value, ComponentTable[2, i].Value, ComponentTable[3, i].Value, ComponentTable[5, i].Value));
                    }
                    else
                    {
                        DBManager.ExecuteNonQuery(String.Format("INSERT INTO Objects ([Name], MTBF, MTTR, [Image]) VALUES ('{0}', {1}, {2}, '{3}');", ComponentTable[1, i].Value, ComponentTable[2, i].Value, ComponentTable[3, i].Value, ComponentTable[5, i].Value));

                        int ID = DBManager.ExecuteScalar("SELECT ID FROM Objects WHERE [Name] = '" + ComponentTable[1, i].Value + "'");

                        ComponentTable[0, i].Value = ID;
                    }
                }
                catch (Exception ex)
                { }
            }

            for (int i = 0; i < DeletedComponents.Count; i++)
            {
                DBManager.ExecuteNonQuery("DELETE FROM Objects WHERE ID = " + DeletedComponents[i]);
            }

            DeletedComponents.Clear();

            return true;
        }

        private void ComponentTable_RowsAdded(object sender, DataGridViewRowsAddedEventArgs e)
        {
            string ImagePath = Directory.GetCurrentDirectory() + "\\Images\\";

            ComponentTable[4, e.RowIndex].Value = Image.FromFile(ImagePath + "Unknown.png");
            ComponentTable[5, e.RowIndex].Value = "Unknown.png";
        }

        private void ComponentTable_UserDeletingRow(object sender, DataGridViewRowCancelEventArgs e)
        {
            try
            {
                if (MessageBox.Show("Delete row?", "Warning", MessageBoxButtons.YesNo) == DialogResult.Yes)
                {
                    DeletedComponents.Add(Int32.Parse(ComponentTable[0, e.Row.Index].Value.ToString()));
                }
                else
                {
                    e.Cancel = true;
                }
            }
            catch (Exception ex)
            { }            
        }

        private void FormComponent_FormClosing(object sender, FormClosingEventArgs e)
        {
            bool b = Save();

            if (!b)
            {
                DialogResult dialogResult = MessageBox.Show("There are errors during saving. Quit without saving?", "Warning", MessageBoxButtons.YesNo);

                if (dialogResult == DialogResult.Yes)
                {
                    DBManager.Close();
                }
                else
                {
                    e.Cancel = true;
                }
            }
        }

        private void SearchText_TextChanged(object sender, EventArgs e)
        {
            Search(ComponentTable, SearchText.Text);
        }

        void Search(DataGridView datagrid, string Search)
        {
            for (int i = 0; i < datagrid.Rows.Count - 1; i++)
            {
                if (i % 2 == 0)
                {
                    for (int j = 1; j < datagrid.Columns.Count; j++)
                    {
                        datagrid[j, i].Style.BackColor = DefaultColor;
                    }
                }
                else
                {
                    for (int j = 1; j < datagrid.Columns.Count; j++)
                    {
                        datagrid[j, i].Style.BackColor = AlternatingDefaultColor;
                    }
                }
            }

            if (SearchText.Text != "")
            {
                for (int i = 0; i < datagrid.Rows.Count - 1; i++)
                {
                    for (int j = 1; j < datagrid.Columns.Count - 1; j++)
                    {
                        if (datagrid[j, i].Value.ToString().Contains(Search))
                        {
                            for (int k = 1; k < datagrid.Columns.Count; k++)
                            {
                                datagrid[k, i].Style.BackColor = Color.FromArgb(180, 255, 180);
                            }
                        }
                    }
                }
            }
        }
    }
}
